package com.alibaba.serverless;

import com.alibaba.fastjson.JSON;
import com.alibaba.serverless.common.ApiGwRequest;
import com.alibaba.serverless.common.ApiGwResponse;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.FunctionComputeLogger;
import com.aliyun.fc.runtime.FunctionInitializer;
import com.aliyun.fc.runtime.PojoRequestHandler;
import com.aliyuncs.utils.Base64Helper;
import com.aliyuncs.utils.StringUtils;

import java.io.UnsupportedEncodingException;

public  class MainHandler implements FunctionInitializer, PojoRequestHandler<ApiGwRequest, ApiGwResponse> {

    /* 云函数初始化
     * @see com.aliyun.fc.runtime.FunctionInitializer#initialize(com.aliyun.fc.runtime.Context)
     */
    @Override
    public void initialize(Context context) {
        FunctionComputeLogger logger = context.getLogger();
        logger.debug(String.format("RequestID is %s %n", context.getRequestId()));
    }

    /* 云函数处理入口
     * @see com.aliyun.fc.runtime.PojoRequestHandler#handleRequest(java.lang.Object, com.aliyun.fc.runtime.Context)
     */
    @Override
    public ApiGwResponse handleRequest(ApiGwRequest request, Context context) {
        FunctionComputeLogger logger = context.getLogger();
        String queryParams = request.getBody();
        context.getLogger().info("请求参数: " + queryParams );
        if (request.getIsBase64Encoded()) {
            // 需要对字符串进行解密，APIGateway协议，参考：https://help.aliyun.com/document_detail/54788.html
            try {
            	queryParams = Base64Helper.decode(queryParams, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.info("解码失败：" + queryParams + ";  失败原因：" + e.getMessage());
            }
            logger.info("解码内容：" + queryParams);
        }

        /**
         * 构建服务返回结果
         */
        String  resultModel = "Hello World！";
        if( ! StringUtils.isEmpty( queryParams )  ){
        	resultModel += " 服务端收到消息: " +  queryParams;
        }
        
        ApiGwResponse response = new ApiGwResponse();
        response.getHeaders().put("responseHeader", "testValue");
        String responseBody = JSON.toJSONString(resultModel);
        
        /**
        boolean isBase = request.getIsBase64Encoded();
         * 响应内容是JSON，不用编码, 建议和 request内部编码保持一致
         * isBase = false;
         *         if (isBase) {
         *             try {
         *                 responseBody = Base64Helper.encode(responseBody, "UTF-8");
         *                 response.setBase64Encoded(true);
         *             } catch (UnsupportedEncodingException e) { // 编码失败，就用原文
         *                 response.setBase64Encoded(false);
         *             }
         *         }
         */
        response.setBase64Encoded(false);
        response.setBody(responseBody);
        response.setStatusCode(200);

        return response;

    }

}
